<template>
  <div class="mx-auto" style="max-width: 600px">
    <!-- <input type="file" name="file" @change.prevent="handleFileChange" /> -->
    <upload
      action="/api/upload"
      :beforeUpload="uploadCheck"
      @file-uploaded="handleFileUploaded"
      :uploaded="uploadedData"
      class="
        d-flex
        align-items-center
        justify-content-center
        text-secondary
        my-4
      "
    >
      <h2>点击上传文章封面</h2>
      <template #loading>
        <div class="d-flex">
          <!-- <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div> -->
          <h3>正在上传</h3>
        </div>
      </template>
      <template #uploaded="dataProps">
        <div class="upload-area">
          <img :src="dataProps.uploadedData.data.url" />
          <h3 class="again">点击重新上传</h3>
        </div>
      </template>
    </upload>
    <validate-form @form-submit="onArticalForm">
      <div class="form-group mb-3">
        <label>文章标题</label>
        <validate-input
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="email"
          ref="inputRef"
          inputType="input"
        />
      </div>
      <div class="form-group mb-3">
        <label>文章内容</label>
        <validate-input
          :rules="contentRules"
          v-model="contentVal"
          placeholder="请输入文章内容"
          type="password"
          inputType="textarea"
        />
      </div>
      <template #submit>
        <button type="submit" class="btn btn-primary">提交文章</button>
      </template>
    </validate-form>
  </div>
</template>
<script lang='ts'>
import { defineComponent, ref, onMounted } from "vue";
import ValidateForm from "./ValidateForm.vue";
import Upload from "./Upload.vue";
import ValidateInput, { RuleProp } from "./ValidateInput.vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import axios from "axios";
import { beforeUploadCheck } from "@/utils/beforeUpload";
import createMessage from "@/utils/createMessage";
import { ResponseType, imageData, ArticalProps } from "@/utils/interface";
export default defineComponent({
  name: "AddArtical",
  components: { ValidateForm, ValidateInput, Upload },
  setup() {
    const titleVal = ref("");
    const contentVal = ref("");
    const uploadedData = ref();
    const titleRules: RuleProp[] = [
      {
        type: "required",
        message: "请输入文章标题",
      },
    ];
    const contentRules: RuleProp[] = [
      {
        type: "required",
        message: "请输入文章内容",
      },
    ];
    const router = useRouter();
    const store = useStore();
    const route = useRoute();
    const isEditMode = !!route.query.id;
    // const isEditMode = false;
    let imageId = "";
    onMounted(() => {
      // 判断是不是点了“编辑”进来的页面
      if (isEditMode) {
        // 发送请求拿到原本文章的数据，赋值给uploadedData，并传到upload组件显示到对应的框里
        store
          .dispatch("fetchPost", route.query.id)
          .then((rawData: ResponseType<ArticalProps>) => {
            // 想通过then拿到数据，那么发送请求的时候要返回一个带有data数据的promise，见request.ts
            const currentPost = rawData.data;
            if (currentPost.image) {
              uploadedData.value = { data: currentPost.image };
            }
            titleVal.value = currentPost.title;
            contentVal.value = currentPost.content || "";
            // 页面上无法显示原来文章的内容？--》双向绑定不成功？？
          });
      }
    });
    // 点击 提交文章
    const onArticalForm = (result: any) => {
      if (result) {
        const { column, _id } = store.state.user;
        if (column) {
          const newPost: ArticalProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id,
            image: {},
          };
          if (imageId && newPost.image) {
            newPost.image._id = imageId;
          }
          const actionName = isEditMode ? "updatePost" : "createPost";
          const sendData = isEditMode
            ? {
                id: route.query.id,
                payload: newPost,
              }
            : newPost;
          store.dispatch(actionName, sendData).then(() => {
            createMessage("发表成功，2秒后跳转到文章", "success", 2000);
            setTimeout(() => {
              router.push({ name: "columndetail", params: { id: column } });
            }, 2000);
          });
        }
      }
    };
    // 上传文章这里需要再学习一下
    const handleFileChange = (e: Event) => {
      const target = e.target as HTMLInputElement;
      const files = target.files;
      if (files) {
        const uploadFile = files[0];
        const formData = new FormData();
        formData.append(uploadFile.name, uploadFile);
        axios
          .post("/api/upload", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((resp) => {
            console.log(resp);
          });
      }
    };

    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, {
        format: ["image/jpeg", "image/png"],
        size: 1,
      });
      const { passed, error } = result;
      if (error === "format") {
        createMessage("上传图片只能是 JPG/PNG 格式!", "error");
      }
      if (error === "size") {
        createMessage("上传图片大小不能超过 1Mb", "error");
      }
      return passed;
    };
    // 接收子组件Upload发送来的事件
    const handleFileUploaded = (rawData: ResponseType<imageData>) => {
      if (rawData.data._id) {
        // 拿到上传图片的id
        imageId = rawData.data._id;
      }
    };
    return {
      titleRules,
      contentRules,
      titleVal,
      contentVal,
      onArticalForm,
      handleFileChange,
      uploadCheck,
      handleFileUploaded,
      uploadedData,
    };
  },
});
</script>
<style scoped>
.upload-area {
  position: relative;
}
.upload-area .again {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
.upload-area:hover .again {
  display: block;
}
</style>